package org.exeed.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.exeed.dao.ModMapper;
import org.exeed.entity.ModEntity;
import org.exeed.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ModService {

    @Autowired
    private ModMapper modMapper;

    public void save(ModEntity entity) {

        entity.setUpdateTime(DateUtil.current());

        if (entity.getId() == null || entity.getId() == 0) {
            entity.setId(JWTUtils.createId());
            modMapper.insert(entity);
        } else {
            modMapper.updateById(entity);
        }

    }

    public Map selectList(Integer page, Integer size, String key) {

        Page<ModEntity> iPage = new Page<>(page, size);
        QueryWrapper<ModEntity> queryWrapper = new QueryWrapper<>();
        if (key != null && !key.equals("")) {
            queryWrapper.like("name", key);
            queryWrapper.orderByDesc("update_time");
        }
        IPage<ModEntity> list = modMapper.selectPage(iPage, queryWrapper);
        Map<String, Object> R = new HashMap<>();
        R.put("page", page);
        R.put("size", size);
        R.put("total", list.getTotal());
        R.put("list", list.getRecords());
        return R;
    }

    public List<ModEntity> selectAll(){
        return  modMapper.selectList(new QueryWrapper<>());
    }

    public ModEntity selectById(Long id) {
        return modMapper.selectById(id);
    }
}
